package com.google.code.porntube.snap.trigger;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.code.porntube.snap.core.setting.Analyzer;

public final class SnapTrigger extends HttpServlet {

	private static final long serialVersionUID = 8212875001417580170L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		Queue queue = QueueFactory.getQueue("snap");
		try {
			DatastoreService datastore = DatastoreServiceFactory
					.getDatastoreService();
			Transaction txn = datastore.beginTransaction();
			int count = 0;
			for(String catalog : Analyzer.CATALOG) {
				count++;
				queue.add(TaskOptions.Builder.withUrl("/tasks/snap")
						.method(TaskOptions.Method.GET).param("catalog", catalog));
				if(count == 5) {
					count = 0;
					txn.commit();
					txn = datastore.beginTransaction();
				}
			}
			if(count > 0) {
				txn.commit();
			}			
		} catch (DatastoreFailureException exception) {
			throw new IOException(exception);
		}
	}
}
